<?php

namespace App\Admin\Controllers;

use App\Models\Book;
use App\Models\BookList;

use App\Models\BookListCategory;
use Carbon\Carbon;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use DB;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class BookListsController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('书单列表');
            //$content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('修改书单');
            //$content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    public function update($id)
    {
        return $this->form()->update($id);
    }

    public function destroy($id)
    {
        //$this->form()->destroy()
        $arr = explode(',',$id);
        BookList::whereIn('id',$arr)->update(['deleted'=>1,'deleted_at'=>Carbon::now()]);
        return ['status'=>true,'message'=>'删除成功'];
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('添加书单');
            //$content->description('description');

            $content->body($this->form());
        });
    }

    public function store()
    {
        return $this->form()->store();
    }

    public function show($id, Content $content)
    {
        return $content
            ->header('书单详情')
            //->description('description')
            ->body($this->detail($id));
    }

    public function sort($book_list_id, $pk, Request $request)
    {
        DB::table('book_list_book_relations')->where('id',$pk)->update([
            'sort' => $request->input('value')
        ]);
        return ['status'=>true,'message'=>'保存成功'];
    }

    public function detail($id)
    {
        $show = new Show(BookList::findOrFail($id));

        $show->panel()
            ->tools(function ($tools) {
                $tools->disableEdit();
                //$tools->disableList();
                $tools->disableDelete();
            });

        $show->title('书单名称');

        $show->divider();
        $show->books('图书列表', function ($books) {
            $books->model()->orderBy('sort','asc');

            $books->title('图书名称');
            $books->sort('排序值')->editable();

            $books->disableCreateButton();
            $books->disableExport();
            $books->disableRowSelector();
            $books->disableActions();
            $books->disableFilter();
            $books->disablePagination();

            $books->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();
            });
        });

        return $show;
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(BookList::class, function (Grid $grid) {
            $grid->model()->where('deleted', 0);
            $grid->model()->ordered();

            //$grid->id('ID')->sortable();
            $grid->title('书单名称');
            $grid->category()->title('书单分类');
            $grid->system_collect_num('系统收藏人数');
            $grid->user_collect_num('真实用户收藏人数');
            $grid->is_recommend('是否首页精选书单')->display(function($value) {
                if(!$value)
                {
                    return '否';
                }
                return '是';
            });
            $grid->order('排序')->orderable();
            //$grid->created_at('添加时间');
            $states = [
                'off' => ['value' => 2, 'text' => '下架', 'color' => 'danger'],
                'on'  => ['value' => 1, 'text' => '上架', 'color' => 'success'],
            ];
            $grid->status('上架状态')->switch($states);
            //$grid->updated_at();
            $grid->actions(function ($actions) {
                //$actions->disableView();
            });

            $grid->disableExport();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($flag = false)
    {
        return Admin::form(BookList::class, function (Form $form) {

            $form->display('id', 'ID');

            $form->text('title', '书单名称')->rules('required');
            $form->select('category_id','书单分类')->options(BookListCategory::getSelectOptions())->rules('required');
            $form->image('list_image', '书单列表封面')->rules('required|image')->uniqueName();
            $form->image('detail_image', '书单详情封面')->rules('required|image')->uniqueName();
            $form->textarea('intro','简介')->rows(10)->rules('required');
            $form->text('system_collect_num', '系统设置收藏用户')->rules('required|integer|min:0');
            //$form->display('created_at', 'Created At');
            //$form->display('updated_at', 'Updated At');
            $form->text('order', '排序')->rules('required|integer|min:0')->default(50);
            $form->radio('is_recommend','是否推荐至首页精选书单')->options(['0' => '否', '1'=> '是'])->default('0');

            $states = [
                'off' => ['value' => 2, 'text' => '下架', 'color' => 'danger'],
                'on'  => ['value' => 1, 'text' => '上架', 'color' => 'success'],
            ];

            $form->switch('status', '是否上架')->states($states);
            //$form->listbox('books','选择书单包含的图书')->options(Book::query()->where('on_sale',1)->where('deleted',0)->get()->pluck('title', 'id'))->settings(['selectorMinimalHeight' => 300]);

            //$form->multipleSelect('books')->options();

            $form->multipleSelect('books','选择书单包含的图书')->options(function ($ids) {
                if($ids)
                {
                    return Book::find($ids)->pluck('title', 'id');
                }
            })->ajax('/api/admin/search/books');

            $form->tools(function (Form\Tools $tools) {
                $tools->disableView();
                $tools->disableDelete();
            });

            // 回调
            $form->saved(function (Form $form) {
                $id = $form->model()->id;
                $order = $form->model()->order;

                $total_collect_num = $form->model()->user_collect_num + $form->model()->system_collect_num;
                //DB::table('book_lists')->where('id',$id)->update(['total_collect_num'=>$total_collect_num,'order'=>$id]);
                DB::table('book_lists')->where('id',$id)->update(['total_collect_num'=>$total_collect_num]);

                //添加假用户收藏数据
                DB::table('book_list_user_collect_relations')->where('book_list_id',$id)->where('user_type',0)->delete();
                if($form->model()->system_collect_num > 0)
                {
                    for ($i = 0; $i < $form->model()->system_collect_num; $i++)
                    {
                        $user_id = random_int(1,2532);
                        $record = DB::table('book_list_user_collect_relations')->where('user_id',$user_id)->where('book_list_id',$id)->first();
                        while ($record)
                        {
                            $user_id = random_int(1,2532);
                            $record = DB::table('book_list_user_collect_relations')->where('user_id',$user_id)->where('book_list_id',$id)->first();
                        }

                        DB::table('book_list_user_collect_relations')->insert([
                            'user_id' => $user_id,
                            'book_list_id' => $id,
                            'user_type' => 0
                        ]);
                    }
                }
            });
        });
    }
}
